package com.hz.friends.serverrequest;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVPush;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.CountCallback;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.SendCallback;
import com.hz.friends.serverrequest.ALCCPEngine.ALMessageOfChatType;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class ALEngineConfig {
	

	static int DEFAULE_LIMITE = 20;
	static boolean USER_AVOS_STATUS = true;
	
	//通用回调
	//接口 不实现 使用时必须实现接口中所有方法
	public interface CallBack {   
	     void done(Object object,AVException avexception);
	} 
	//抽象类 可实现 使用时不必须重现所有方法
//	public abstract class CallBack {   
//	     void done(Object object,AVException avexception){
//	};
//	} 
	
	//当前用户
	public static AVUser user() {    
		return AVUser.getCurrentUser();
	}
	
	//是否已登录
	public static  Boolean isLoggedIn() {    
		return ALEngineConfig.user()!=null &&ALEngineConfig.user().isAuthenticated();
	}
	
	//PHOTO
	public enum ALPhotoType {  
		
		ALPhotoTypeOfUndefine("未知",0), 
		ALPhotoTypeOfOfficial("官方图片",1), 
		ALPhotoTypeOfUser("用户上传图片",2), 
		ALPhotoTypeOfFouce("焦点图片",11),
		ALPhotoTypeOfAdvertisement("广告图片",21);
		
	    private int _value;
	    private String _name;
	    
	    private ALPhotoType(String name, int value)
	    {
	    	_name = name;
	    	_value = value;
	    }
	     
	    public String get_name() {
			return _name;
		}
	    
		public int get_value() {
			return _value;
		}
	} 
	
	//PUSH
		public enum ALPushType {  
			
			ALPushTypeOfUndefine("未知",0), 
			ALPushTypeOfMessageOfChat("chat",1), 
			ALPushTypeOfNewFollow("关注",2), 
			ALPushTypeOfGift("礼物",3),
			ALPushTypeOfMessageOfBBs("李艳",4),
			ALPushTypeOfSpecialRemind("特别提醒",5);
			
		    private int _value;
		    private String _name;
		    
		    private ALPushType(String name, int value)
		    {
		    	_name = name;
		    	_value = value;
		    }
		     
		    public String get_name() {
				return _name;
			}
		    
			public int get_value() {
				return _value;
			}
		} 
	
	/*
	 *  第三方登陆type
	 */
	public enum ALAccessTokenType {  
		
		ALAccessTokenTypeOfUndefined("未知",0), 
		ALAccessTokenTypeOfSinaWeiBo("新浪微博",1),
	    ALAccessTokenTypeOfTencentWeiBo("腾讯微博",2),
	    ALAccessTokenTypeOfQQ("qq",3),
	    ALAccessTokenTypeOfWeChat("微信",4),
	    ALAccessTokenTypeOfRenren("人人",5),
	    ALAccessTokenTypeOfFacebook("facebook",6),
	    ALAccessTokenTypeOfTwitter("推特",7);
		
	    private int _value;
	    private String _name;
	    
	    private ALAccessTokenType(String name, int value)
	    {
	    	_name = name;
	    	_value = value;
	    }
	     
	    public String get_name() {
			return _name;
		}
	    
		public int get_value() {
			return _value;
		}
	} 
	
	/*
	 * 性别
	 * 
	 */
	public enum ALUserGender {  
		
		ALUserGenderOfUndefine("未知",0), 
		ALUserGenderOfMale("男性",1),
		ALUserGenderOfFemale("女性",2);

	    private int _value;
	    private String _name;
	    
	    private ALUserGender(String name, int value)
	    {
	    	_name = name;
	    	_value = value;
	    }
	     
	    public String get_name() {
			return _name;
		}
	    
		public int get_value() {
			return _value;
		}
	} 
	
	/*
	 * 性取向
	 * 
	 */
	public enum ALSexualOrientation {  
		
		ALSexualOrientationOfUndefine("未知",0), 
		ALSexualOrientationOfHomosexual("男性",1),
		ALSexualOrientationOfHeterosexual("女性",2),
		ALSexualOrientationOfBisexuality("双性",3);

	    private int _value;
	    private String _name;
	    
	    private ALSexualOrientation(String name, int value)
	    {
	    	_name = name;
	    	_value = value;
	    }
	     
	    public String get_name() {
			return _name;
		}
	    
		public int get_value() {
			return _value;
		}
	} 
	
	
	/*
	 * 用户关系
	 * 
	 */
	public enum ALUserRelationType {  
		
		ALUserRelationTypeOfNone("未知",0), 
		ALUserRelationTypeOfFollow("关注",1),
		ALUserRelationTypeOfBan("黑名单",-1);

	    private int _value;
	    private String _name;
	    
	    private ALUserRelationType(String name, int value)
	    {
	    	_name = name;
	    	_value = value;
	    }
	     
	    public String get_name() {
			return _name;
		}
	    
		public int get_value() {
			return _value;
		}
	} 
	
	
	
	public static AVObject objectWithoutData(AVObject object){
		if (object.getObjectId()==null) return object;
		return AVObject.createWithoutData(object.getClassName(), object.getObjectId());
	}
	
	
		
		public static void _includeKeyWithGiftCount(AVQuery giftCountQ){
			
			if (giftCountQ.getClassName().equals("GiftCount"))
			{
				giftCountQ.include("gift");
			}
		}
		
		public static void _includeKeyWithUserRelation(AVQuery userRelationQ){
			
			if (userRelationQ.getClassName().equals("UserRelation"))
			{
				userRelationQ.include("toUser");
				userRelationQ.include("fromUser");
			}
		}
		
		public static void _includeKeyWithMessageOfBBS(AVQuery messageOfBBSQ){
			
			if (messageOfBBSQ.getClassName().equals("MessageOfBBS"))
			{
				messageOfBBSQ.include("toUser");
				messageOfBBSQ.include("fromUser");
				messageOfBBSQ.include("giftRecorder");
			}
		}
		
		public static void _includeKeyWithGiftRecorder(AVQuery giftRecorderQ){
			
			if (giftRecorderQ.getClassName().equals("GiftRecorder"))
			{
				giftRecorderQ.include("fromUser");
			}
		}
		
		
		
		public static void findObjectsInBackground(
				AVQuery<AVObject> query,
				final String key,
				final CallBack listCallback){
			query.findInBackground(new FindCallback<AVObject>() {

				@Override
				public void done(List<AVObject> objects, AVException e) {
					// TODO Auto-generated method stub
					ArrayList<Object> values = new ArrayList<Object>();
					if(objects == null){
						listCallback.done(values,e);
                       return;
					}
					for (AVObject object : objects)
					{
						Object obj = object.get(key);
						if (obj!=null) values.add(obj);
					}
					listCallback.done(values,e);
				}
			});
		}
	
	//include---user
	public static void _includeKeyWithUser( AVQuery friendsQ){
		
		if (friendsQ.getClassName().equals("_User"))
		{
			friendsQ.include("contacts");
//			friendsQ.include("userInfo");
//			friendsQ.include("userCount");
//			friendsQ.include("userFavicon");
		}
	}
	
	//include---follow
//	public static void _includeKeyWithFollow( AVQuery<AVObject>  followQ){
//		
//			followQ.include("followee");
//			followQ.include("follower");
//	}
	
	//include---message
	public static void _includeKeyWithMessage( AVQuery<AVObject>  messageQ){
		
		if (messageQ.getClassName().equals("Message"))
		{
			messageQ.include("fromUser");
			messageQ.include("toUser");
			messageQ.include("content");
		}
	}
	
	//include---comment
	public static void _includeKeyWithComment( AVQuery<AVObject>  commentQ){
		
		if (commentQ.getClassName().equals("Comment"))
		{
			commentQ.include("content");
			commentQ.include("photo");
			commentQ.include("user");
		}
	}
	
	//include---photo
	public static void _includeKeyWithPhoto( AVQuery<AVObject>  photoQ){

		if (photoQ.getClassName().equals("Photo"))
		{
			photoQ.include("content");
			photoQ.include("brand");
			photoQ.include("temperature");
			photoQ.include("user");
			photoQ.include("collocation");
			
			photoQ.whereExists("height");
			photoQ.whereExists("width");
			photoQ.whereExists("thumbnailURL");
			photoQ.whereExists("originalURL");
		}
	}

	//include---schedule
	public static void _includeKeyWithSchedule( AVQuery<AVObject>  scheduleQ){
		
		if (scheduleQ.getClassName().equals("Schedule"))
		{
			scheduleQ.include("content");
			scheduleQ.include("push");
			scheduleQ.include("user");
		}	
	}
	
	//通用relation请求
	public static void _commomRelationQueryRequest(final AVObject object, final String relationKey, final int limit, final int skip, final Boolean isCount, final CallBack callback) {    
		if (object==null || object.getObjectId()==null)
		{
			callback.done(false, new AVException(1, "没有登录"));
			return;
		}
 		
		AVQuery<AVObject> query = null;
        try {
        	query = object.getRelation(relationKey).getQuery();
        	ALEngineConfig._addLimit(limit, skip, query);
        	ALEngineConfig._includeKeyWithUser(query);
    		ALEngineConfig._includeKeyWithPhoto(query);
    		ALEngineConfig._includeKeyWithComment(query);
    		ALEngineConfig._includeKeyWithSchedule(query);
    		
    		if (isCount)
    		{
    			query.countInBackground(new CountCallback() {
    				  public void done(int count, AVException e) {
    					  callback.done(count, e);
    					  }
    					});
    		}
    		else
    		{
    			query.findInBackground(new FindCallback<AVObject>() {
    			    public void done(List<AVObject> results, AVException e) {
    			    	callback.done(results, e);
    			      }
    			    });
    		}
		} catch (Exception e) {
			e.printStackTrace();
			if(isCount)
				 callback.done(0, null);
			else
				callback.done(null, null);
			return;
		}
		
		
	}
			
	//通用分页
	//YYYY-MM-DD HH:mm:ss
	public static void _addLimitWithDate(
			final int limit, 
			final Date lessThenDate, 
			AVQuery<AVObject> query) {    
		
		if (limit!=0)
	    {
			query.setLimit(limit);
	    }
	    else
	    {
	    	query.setLimit(DEFAULE_LIMITE);
	    }
	    
	    if (lessThenDate!=null)
	    {
//	    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			String lessThenDateStr = simpleDateFormat.format(lessThenDate);
	    	query.whereLessThan("createdAt", lessThenDate);
	    }
	    query.orderByDescending("createdAt");
	}
	
	//YYYY-MM-DD HH:mm:ss
		public static void _addLimit(final int limit,  final int skip, AVQuery query) {    
			if (limit > 0)
		    {
				query.setLimit(limit);
		    }
		    else
		    {
		    	query.setLimit(DEFAULE_LIMITE);
		    }
		    
		    if (skip > 0)
		    {
		    	query.skip(skip);
		    }
		    else
		    {
		    	query.skip(0);
		    }
		}
		
		public static void _addRelation(
				final AVQuery<AVObject> aQuery,  
				final AVObject aObject, 
				final CallBack boolCallback) {    
			
			aQuery.limit(1);
			aQuery.findInBackground(new FindCallback<AVObject>() {

				@Override
				public void done(List<AVObject> objects, AVException e) {
					//网络错误（超时）
					if (e != null)
					{
						boolCallback.done(false,e);
					}
					//已经收藏
					else if (objects.size()!=0)
					{
						boolCallback.done(false,new AVException(110, "已经存在"));
					}
					else
					{
						aObject.saveInBackground(new SaveCallback() {
							
							@Override
							public void done(AVException e) {
								boolCallback.done(e==null,e);
							}
						});
					}
				}
			});
		}
		
		public static void _removeRelation(
				final AVQuery<AVObject> aQuery,  
				final CallBack boolCallback) {    
			aQuery.getFirstInBackground(new GetCallback<AVObject>() {

				@Override
				public void done(AVObject object, AVException e) {
					//已经存在
					if (object != null)
					{
						object.deleteInBackground(new DeleteCallback() {
							
							@Override
							public void done(AVException e) {
								// TODO Auto-generated method stub
								boolCallback.done(e==null,e);
							}
						});
					}
					else
					{
						boolCallback.done(false,new AVException(110, "不存在"));
					}
				}
			});
		}
		
		public static void _checkNumberOfCommtents(
				final AVUser theUser,  
				final AVObject thePhoto) {    
			if (thePhoto != null)
			{
				AVQuery<AVObject> commentQ = new AVQuery<AVObject>("Comment");
				commentQ.whereEqualTo("photo", thePhoto);
				commentQ.countInBackground(new CountCallback() {
					
					@Override
					public void done(int number, AVException e) {
						// TODO Auto-generated method stub
						thePhoto.put("numberOfComments", number);
						thePhoto.saveEventually();
					}
				});
			}
			
			if (theUser != null)
			{
				AVQuery<AVObject> commentQ = new AVQuery<AVObject>("Comment");
				commentQ.whereEqualTo("user", theUser);
				commentQ.countInBackground(new CountCallback() {
					
					@Override
					public void done(int number, AVException e) {
						// TODO Auto-generated method stub
						theUser.put("numberOfCommtentPhotos", number);
						theUser.saveEventually();
					}
				});
			}
		}
		
		public static void _checkNumberOfFavicons(
				final AVUser theUser,  
				final AVObject thePhoto) {    
			if (thePhoto != null)
			{
				AVQuery<AVObject> relationQ = new AVQuery<AVObject>("Relation");
				relationQ.whereEqualTo("photo", thePhoto);
				relationQ.countInBackground(new CountCallback() {
					
					@Override
					public void done(int number, AVException e) {
						// TODO Auto-generated method stub
						thePhoto.put("numberOfFavicons", number);
						thePhoto.saveEventually();
					}
				});
			}
			
			if (theUser != null)
			{
				AVQuery<AVObject> relationQ = new AVQuery<AVObject>("Relation");
				relationQ.whereEqualTo("user", theUser);
				relationQ.countInBackground(new CountCallback() {
					
					@Override
					public void done(int number, AVException e) {
						// TODO Auto-generated method stub
						theUser.put("numberOfFaviconPhotos", number);
						theUser.saveEventually();
					}
				});
			}
		}
		
		public static void _request(
				String requestUrl, 
				String authorization, 
				String xmlBody, 
				int timeOut, 
				final CallBack stringCallback) {

			AsyncHttpClient client = new AsyncHttpClient();
			client.addHeader("Accept", "application/xml");
	        client.addHeader("Content-Type", "application/xml;charset=utf-8");
	        client.addHeader("Authorization", "authorization");
	        try {
				client.post(requestUrl + "'" + new String(xmlBody.getBytes(), "UTF-8") + "'",new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(String response) {
						stringCallback.done(response, null);
					}

					public void onFailure(Throwable arg0) {
						stringCallback.done(null, new AVException(arg0));
					};
				});
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public static void sendPushToInstalQuery(
				AVQuery theInstallQ,
				ALPushType type,
				ALMessageOfChatType subType){
			
			String alertStr = ALEngineConfig.getAlertStringWithType(type, subType);
			if (alertStr==null)
			{
				return;
			}
			
		}
		
		private static String getAlertStringWithType(
				ALPushType theType,
				ALMessageOfChatType theSubType){
			
			String nickname = AVUser.getCurrentUser().getString("nickname");
			String alertStr = null;
			
			switch (theType)
		    {
		        case ALPushTypeOfNewFollow:
		        {
		            if (nickname==null)
		            {
		                alertStr = nickname+" : "+"[关注]";
		            }
		            else
		            {
		                alertStr = "你有一个新的粉丝";
		            }
		        }
		            break;
		        case ALPushTypeOfGift:
		        {
		            if (nickname==null)
		            {
		                alertStr = nickname+" : "+"[礼物]";
		            }
		            else
		            {
		                alertStr = "你收到一份礼物";
		            }
		        }
		            break;
		        case ALPushTypeOfMessageOfBBs:
		        {
		            if (nickname==null)
		            {
		                alertStr = nickname+" : "+"[留言]";
		            }
		            else
		            {
		                alertStr ="你收到一个新的留言";
		            }
		        }
		            break;
		        case ALPushTypeOfSpecialRemind:
		        {
		            if (nickname==null)
		            {
		                alertStr = nickname+" : "+"[上线]";
		            }
		            else
		            {
		                alertStr = "你的特别关注上线了";
		            }
		        }
		            break;
		        case ALPushTypeOfMessageOfChat:
		        {
		            switch (theSubType) {
		                case ALMessageOfChatTypeOfText:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[文字]";
		                    }
		                    else
		                    {
		                        alertStr = "你收到一条消息";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfVoice:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[语音]";
		                    }
		                    else
		                    {
		                        alertStr = "你收到一段[语音]";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfImage:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[图片]";
		                    }
		                    else
		                    {
		                        alertStr = "你收到一个[图片]";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfVideo:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[视频]";
		                    }
		                    else
		                    {
		                        alertStr ="你收到一段[视频]";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfGroupInvite:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[群邀请]";
		                    }
		                    else
		                    {
		                        alertStr ="你收到一个[群邀请]";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfLocation:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[位置]";
		                    }
		                    else
		                    {
		                        alertStr = "你收到一个[位置]";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfFile:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[文件]";
		                    }
		                    else
		                    {
		                        alertStr = "你收到一个[文件]";
		                    }
		                }
		                    break;
		                case ALMessageOfChatTypeOfCommand:
		                {
		                    if (nickname==null)
		                    {
		                        alertStr = nickname+" : "+"[command]";
		                    }
		                    else
		                    {
		                        alertStr = "你收到一个[command]";
		                    }
		                }
		                    break;
		                default:
		                    break;
		            }
		        }
		            break;
		        
		        default:
		            break;
		    }

			return alertStr;
		}
}
